import type { NextFunction, Request, Response } from 'express'
import logger from '../utils/logger'
const convertParams = ['pageSize', 'pageNo', 'userId', 'id', 'questionId', 'createBy']
export type NumParams = {
  [key in typeof convertParams[number]]?: number
}
// 自定义中间件来处理 id 参数的类型转换
export function convertIdMiddleware(req: Request, res: Response, next: NextFunction) {
  // 默认转行这些参数
  const result: NumParams = {}
  let convertResult
  convertParams.forEach((row) => {
    if (typeof req.query?.[row] === 'string') {
      convertResult = parseInt(req.query[row] as string)
      if (!isNaN(convertResult)) {
        result[row] = convertResult
      }
    }
  })
  if (req.body === undefined) {
    req.body = {}
  }
  // 将处理后的 id 存储在请求对象中以供后续中间件或路由使用
  req.body.params = result
  logger.info('convertParams:', result)
  // 继续执行下一个中间件或路由处理
  next()
}
